﻿//-----------------------------------------------------------------------
// <copyright file="AsADistributorAdministratorIShoudAccessTenantsListSeeNoneCreateANewTenantAccessTenantsListAndSeeOne.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Utility.Tests.UI.Web.Behaviour.Tenant{    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Kernel.Factories;
    using AbstractSaaSTemplate.UI.Web.Controllers;
    using AbstractSaaSTemplate.UI.Web.Models.Tenant;
    using AbstractSaaSTemplate.UI.Web.Models.User;
    using AbstractSaaSTemplate.Utility.Tests.UI.Utilities;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    /// <summary>
    /// @13919625
    /// Como Administrador de Distribuidor, eu deveria ser capaz de acessar a
    /// função de acesso controlado "Gerenciamento de Licenciados" e visualizar
    /// uma lista de tenants vazia e, posteriormente, acessar a função de acesso
    /// controlado "Criação ou Edição de Licenciado", criar um Licenciado e, após
    /// este processo, receber este Licenciado cadastrado na função controlada
    /// "Gerenciamento de Licenciados"
    /// </summary>
    [TestClass]
    public class TestFor0013919625
    {
        #region Constants

        /// <summary>
        /// Defines the e-mail address of the tenant administrator that is being created here.
        /// </summary>
        public const string TenantAdministratorEmailAddress = "admin@itbeat.com";

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the Tenant controller which will be used in tests.
        /// </summary>
        private TenantController TenantController { get; set; }

        /// <summary>
        /// Gets or sets the controller that will be used for checking authentication.
        /// </summary>
        private UserController UserController { get; set; }

        /// <summary>
        /// Gets or sets the original quantity of entries to be compared later.
        /// </summary>
        private int OriginalQty { get; set; }

        #endregion

        #region Setup

        /// <summary>
        /// This method initializes controllers and dependencies for run tests.
        /// </summary>
        [TestInitialize]
        public void Setup()
        {
            TestFor0013453151.EnsureInstallationIsComplete();
            
            var factory = new ApplicationFactory();

            this.UserController = factory.CreateControllerFor<UserController>();
            this.TenantController = factory.CreateControllerFor<TenantController>();
        }

        #endregion

        /// <summary>
        /// @13919625
        /// Como Administrador de Distribuidor, eu deveria ser capaz de acessar a
        /// função de acesso controlado "Gerenciamento de Licenciados" e visualizar
        /// uma lista de tenants vazia e, posteriormente, acessar a função de acesso
        /// controlado "Criação ou Edição de Licenciado", criar um Licenciado e, após
        /// este processo, receber este Licenciado cadastrado na função controlada
        /// "Gerenciamento de Licenciados"
        /// Passos da Mímica --------------------------------------------------
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// 2.  Acessar a lista de tenants licenciados. (tenant/ListTenants)
        ///     Deve assegurar:
        ///     2.1) A lista é vazia.
        /// 3.  Criar um tenant licenciado.
        ///     Deve assegurar:
        ///     3.2) Que o tenant foi criado.
        /// 4.  Editar o tenant recém criado.
        ///     Deve assegurar:
        ///     4.1) Que o tenant editado é o mesmo recém criado.
        ///     4.2) Que os campos alterados foram realmente alterados.
        /// 5.  Acessar a lista de tenants licenciados. (tenant/ListTenants)
        ///     Deve assegurar:
        ///     5.1) Que existe um tenant na listagem.
        ///     5.2) Que o tenant seja o mesmo tenant que foi criado anteriormente.
        /// </summary>
        [TestMethod]
        public void AsADistributorAdministratorIShoudAccessTenantsListSeeNoneCreateANewTenantAccessTenantsListAndSeeOne()
        {
            /* =========================================================
             * EXECUÇÃO DA MÍMICA
             * =========================================================
             * Os procedimentos executados à seguir são uma mímica dos
             * procedimentos executados pelos usuários no uso real do sistema.
             * ========================================================= */

            // 1)
            this.LogOnAndAssertActiveUser();

            // 2)
            this.OriginalQty = this.TenantController.RepositoryForTenancy.Tenants.Count();
            this.AssertThatNotExistsTenants();
            
            // 3)
            var createdTenant = this.CreateTenantAndEnsureItExists();

            // 4)
            var editedTenant = this.EditTenantAndEnsureThatItWasEdited(createdTenant);

            // 5)
            this.AssertThatRecentlyCreatedTenantIsShowedInListTenants(editedTenant);
        }

        /// <summary>
        /// 1.  Executa o Logon com usuário pertinente
        ///     Deve assegurar:
        ///     1.1) Que o usuário está logado (activeUser)
        /// </summary>
        private void LogOnAndAssertActiveUser()
        {
            var distributorAdmin = this.UserController.RepositoryForMembership.GetUsersByRole(
                AccessLevels.Distributor,
                AccessRoles.Administrator).FirstOrDefault();

            this.UserController.MockForTesting("LogOn", HttpVerbs.Post);
            this.UserController.LogOn(
                new LogOnForm()
                {
                    Login = distributorAdmin.Credentials.Login,
                    Password = distributorAdmin.Credentials.RetrievePassword()
                },
                string.Empty);

            var activeUser = this.UserController.ServiceForMembership.ActiveUser;
            Assert.IsNotNull(activeUser);
        }
        
        /// <summary>
        /// 2.  Acessar a lista de tenants licenciados. (tenant/ListTenants)
        ///     Deve assegurar:
        ///     2.1) A lista é vazia.
        /// </summary>
        private void AssertThatNotExistsTenants()
        {
            // get the original quantity
            var originalQty = this.TenantController.RepositoryForTenancy.Tenants.Count();
            
            // Mock controller for testing.
            this.TenantController.MockForTesting("ListTenants", HttpVerbs.Get);

            // Perform list of tenants.
            var actionResult = this.TenantController.ListTenants();

            // Assert that result is view result.
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));

            // Get view result.
            var viewResult = actionResult as ViewResult;

            // Assert that model passed in action is an IEnumerable<Tenant>.
            Assert.IsInstanceOfType(viewResult.Model, typeof(IEnumerable<Domain.Models.Entities.Tenant>));

            // Get model,
            var model = viewResult.Model as IEnumerable<Domain.Models.Entities.Tenant>;

            // Assert that exists 0 tenants.
            Assert.AreEqual<int>(originalQty, model.Count());
        }

        /// <summary>
        /// 3.  Criar um tenant licenciado. 
        ///     Deve assegurar: 
        ///     3.2) Que o tenant foi criado.
        /// </summary>
        /// <returns>The tenant created.</returns>
        private Tenant CreateTenantAndEnsureItExists()
        {
            // data for create a tenant
            var model = new CreateOrEditTenantForm();
            model.KeyOrLocation = "tenant-test";
            model.AdministratorEmailAddress = TenantAdministratorEmailAddress;
            model.AdministratorFirstName = "AdministratorFirstName";
            model.AdministratorLastName = "AdministratorLastName";
            model.BillingAddressCity = "BillingAddressCity";
            model.BillingAddressCountryCode = "55";
            model.BillingAddressLine1 = "BillingAddressLine1";
            model.BillingAddressLine2 = "BillingAddressLine2";
            model.BillingAddressLine3 = "BillingAddressLine3";
            model.BillingAddressPostalCode = "099990410";
            model.BillingAddressState = "BillingAddressState";
            model.CompanyName = "CompanyName";
            model.ContactAddressCity = "ContactAddressCity";
            model.ContactAddressCountryCode = "55";
            model.ContactAddressLine1 = "ContactAddressLine1";
            model.ContactAddressLine2 = "ContactAddressLine2";
            model.ContactAddressLine3 = "ContactAddressLine3";
            model.ContactAddressPostalCode = "099990410";
            model.ContactAddressState = "ContactAddressState";
            model.ContactPhoneAreaCode = "11";
            model.ContactPhoneExtension = "909";
            model.ContactPhoneNumber = "90903040";
            model.ContactUsesTheSameAddressAsBilling = false;
            model.DisplayName = "DisplayName";

            // Clear model state for perform new test.
            this.TenantController.ModelState.Clear();

            // Mock controller.
            this.TenantController.MockForTesting("CreateOrEditTenant", HttpVerbs.Post);

            // Perform create tenant.
            var actionResult = this.TenantController.CreateOrEditTenant(null, model);

            // Check validation.
            Assert.IsTrue(this.TenantController.ModelState.IsValid);

            // Assert that action return redirect.
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));

            // Get tenants from tenant repository.
            var tenants = this.TenantController
                .RepositoryForTenancy
                .Tenants
                .Where(d =>
                    d.Website == model.Website &&
                    d.Key == model.KeyOrLocation &&
                    d.DisplayName == model.DisplayName &&
                    d.CompanyName == model.CompanyName &&
                    
                    d.ContactPhone.AreaCode == model.ContactPhoneAreaCode &&
                    d.ContactPhone.Number == model.ContactPhoneNumber &&
                    d.ContactPhone.Extension == model.ContactPhoneExtension &&

                    d.BillingAddress.Line1 == model.BillingAddressLine1 &&
                    d.BillingAddress.Line2 == model.BillingAddressLine2 &&
                    d.BillingAddress.Line3 == model.BillingAddressLine3 &&
                    d.BillingAddress.City == model.BillingAddressCity &&
                    d.BillingAddress.State == model.BillingAddressState &&
                    d.BillingAddress.CountryCode == model.BillingAddressCountryCode &&
                    d.BillingAddress.PostalCode == model.BillingAddressPostalCode &&

                    d.ContactAddress.Line1 == model.ContactAddressLine1 &&
                    d.ContactAddress.Line2 == model.ContactAddressLine2 &&
                    d.ContactAddress.Line3 == model.ContactAddressLine3 &&
                    d.ContactAddress.City == model.ContactAddressCity &&
                    d.ContactAddress.State == model.ContactAddressState &&
                    d.ContactAddress.CountryCode == model.ContactAddressCountryCode &&
                    d.ContactAddress.PostalCode == model.ContactAddressPostalCode)
                .ToList();

            // Check if tenant was created.
            Assert.AreEqual<int>(1, tenants.Count());

            return tenants.FirstOrDefault();
        }

        /// <summary>
        /// 4.  Editar o tenant recém criado.
        ///     Deve assegurar:
        ///     4.1) Que o tenant editado é o mesmo recém criado.
        ///     4.2) Que os campos alterados foram realmente alterados.
        /// </summary>
        /// <param name="createdTenant">The recently created tenant.</param>
        /// <returns>The tenant edited.</returns>
        private Tenant EditTenantAndEnsureThatItWasEdited(Tenant createdTenant)
        {
            // data for edit a tenant
            var model = new CreateOrEditTenantForm();
            long id = createdTenant.Id;
            model.KeyOrLocation = "editted-tenant-test";
            model.AdministratorEmailAddress = string.Concat("editted-", TenantAdministratorEmailAddress);
            model.AdministratorFirstName = "editted-AdministratorFirstName";
            model.AdministratorLastName = "editted-AdministratorLastName";
            model.BillingAddressCity = "editted-BillingAddressCity";
            model.BillingAddressCountryCode = "66";
            model.BillingAddressLine1 = "editted-BillingAddressLine1";
            model.BillingAddressLine2 = "editted-BillingAddressLine2";
            model.BillingAddressLine3 = "editted-BillingAddressLine3";
            model.BillingAddressPostalCode = "000000000";
            model.BillingAddressState = "editted-BillingAddressState";
            model.CompanyName = "editted-CompanyName";
            model.ContactAddressCity = "editted-ContactAddressCity";
            model.ContactAddressCountryCode = "66";
            model.ContactAddressLine1 = "editted-ContactAddressLine1";
            model.ContactAddressLine2 = "editted-ContactAddressLine2";
            model.ContactAddressLine3 = "editted-ContactAddressLine3";
            model.ContactAddressPostalCode = "000000000";
            model.ContactAddressState = "editted-ContactAddressState";
            model.ContactPhoneAreaCode = "66";
            model.ContactPhoneExtension = "000";
            model.ContactPhoneNumber = "00000000";
            model.ContactUsesTheSameAddressAsBilling = false;
            model.DisplayName = "editted-DisplayName";

            // Clear model state for perform new test.
            this.UserController.ModelState.Clear();

            // Perform edit.
            var actionResult = this.TenantController.CreateOrEditTenant(id, model);

            // Check validation.
            Assert.IsTrue(this.TenantController.ModelState.IsValid);

            // Assert that action return redirect.
            Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));

            // Get tenants from tenant repository and check if recently created exists.
            var tenant = this.TenantController
                .RepositoryForTenancy
                .GetTenantById(id);

            // Check if user was edited.
            Assert.IsNotNull(tenant);

            // Check if tenant was not duplicated.
            Assert.AreEqual<string>(tenant.CompanyName, model.CompanyName);
            Assert.AreEqual<string>(tenant.DisplayName, model.DisplayName);
            Assert.AreEqual<string>(tenant.Website, model.Website);

            Assert.AreEqual<string>(tenant.ContactPhone.AreaCode, model.ContactPhoneAreaCode);
            Assert.AreEqual<string>(tenant.ContactPhone.Number, model.ContactPhoneNumber);
            Assert.AreEqual<string>(tenant.ContactPhone.Extension, model.ContactPhoneExtension);

            Assert.AreEqual<string>(tenant.ContactAddress.Line1, model.ContactAddressLine1);
            Assert.AreEqual<string>(tenant.ContactAddress.Line2, model.ContactAddressLine2);
            Assert.AreEqual<string>(tenant.ContactAddress.Line3, model.ContactAddressLine3);
            Assert.AreEqual<string>(tenant.ContactAddress.City, model.ContactAddressCity);
            Assert.AreEqual<string>(tenant.ContactAddress.State, model.ContactAddressState);
            Assert.AreEqual<string>(tenant.ContactAddress.CountryCode, model.ContactAddressCountryCode);
            Assert.AreEqual<string>(tenant.ContactAddress.PostalCode, model.ContactAddressPostalCode);

            Assert.AreEqual<string>(tenant.BillingAddress.Line1, model.BillingAddressLine1);
            Assert.AreEqual<string>(tenant.BillingAddress.Line2, model.BillingAddressLine2);
            Assert.AreEqual<string>(tenant.BillingAddress.Line3, model.BillingAddressLine3);
            Assert.AreEqual<string>(tenant.BillingAddress.City, model.BillingAddressCity);
            Assert.AreEqual<string>(tenant.BillingAddress.State, model.BillingAddressState);
            Assert.AreEqual<string>(tenant.BillingAddress.CountryCode, model.BillingAddressCountryCode);
            Assert.AreEqual<string>(tenant.BillingAddress.PostalCode, model.BillingAddressPostalCode);

            return tenant;
        }

        /// <summary>
        /// 5.  Acessar a lista de tenants licenciados. (tenant/ListTenants)
        ///     Deve assegurar:
        ///     5.1) Que existe um tenant na listagem.
        ///     5.2) Que o tenant seja o mesmo tenant que foi criado anteriormente.
        /// </summary>
        /// <param name="editedTenant">The edited tenant.</param>
        private void AssertThatRecentlyCreatedTenantIsShowedInListTenants(Tenant editedTenant)
        {
            // Mock controller for testing.
            this.TenantController.MockForTesting("ListTenants", HttpVerbs.Get);

            // Perform list of tenants.
            var actionResult = this.TenantController.ListTenants();

            // Assert that result is view result.
            Assert.IsInstanceOfType(actionResult, typeof(ViewResult));

            // Get view result.
            var viewResult = actionResult as ViewResult;

            // Assert that model passed in action is an IEnumerable<Tenant>.
            Assert.IsInstanceOfType(viewResult.Model, typeof(IEnumerable<Domain.Models.Entities.Tenant>));

            // Get model,
            var model = viewResult.Model as IEnumerable<Domain.Models.Entities.Tenant>;

            // Assert that exists 1 tenant.
            Assert.AreEqual(this.OriginalQty + 1, model.Count());

            // Get tenant.
            var tenant = model.LastOrDefault();

            // Assert that listed tenant and edited tenant are same.
            Assert.AreEqual<long>(
                editedTenant.Id,
                tenant.Id);
        }
    }
}


